package org.telegram.bot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.telegram.bot.domain.BotGroup;
import org.telegram.bot.domain.BotKeyWordReply;
import org.telegram.bot.domain.BotKeyboard;
import org.telegram.bot.handle.IBotSendMessage;
import org.telegram.bot.mapper.BotKeyWordReplyMapper;
import org.telegram.bot.mq.producer.GroupCacheRefreshProducer;
import org.telegram.bot.service.IBotChatMemberService;
import org.telegram.bot.service.IBotGroupService;
import org.telegram.bot.service.IBotKeyWordReplyService;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 关键词回复Service业务层处理
 *
 * @author wyx
 * @date 2024-11-24
 */
@Slf4j
@Service
public class BotKeyWordReplyServiceImpl implements IBotKeyWordReplyService, IBotSendMessage
{
    @Resource
    private BotKeyWordReplyMapper botKeyWordReplyMapper;

    @Resource
    private IBotChatMemberService botChatMemberService;
    
    @Lazy
    @Resource
    private IBotGroupService botGroupService;
    
    @Resource
    private GroupCacheRefreshProducer groupCacheRefreshProducer;
    /**
     * 查询关键词回复
     *
     * @param id 关键词回复主键
     * @return 关键词回复
     */
    @Override
    public BotKeyWordReply selectBotKeyWordReplyById(Long id)
    {
        return botKeyWordReplyMapper.selectById(id);
    }

    /**
     * 查询关键词回复列表
     *
     * @param botKeyWordReply 关键词回复
     * @return 关键词回复
     */
    @Override
    public List<BotKeyWordReply> selectBotKeyWordReplyList(BotKeyWordReply botKeyWordReply)
    {
        List<Long> joinChatList = botChatMemberService.getJoinChatList();
        if(!CollectionUtils.isEmpty(joinChatList)){
            botKeyWordReply.setChatIds(joinChatList);
        }else{
            return new ArrayList<>();
        }
        List<BotKeyWordReply> botKeyWordReplies = botKeyWordReplyMapper.selectBotKeyWordReplyList(botKeyWordReply);
        if(!CollectionUtils.isEmpty(botKeyWordReplies)){
            Map<Long, BotGroup> groupMap = botGroupService.selectGroupToMap(joinChatList);
            for (BotKeyWordReply keyWordReply : botKeyWordReplies) {
                BotGroup botGroup = groupMap.get(keyWordReply.getChatId());
                if(botGroup!=null){
                    keyWordReply.getParams().put("chatName",botGroup.getTitle());
                }
            }
        }
        return botKeyWordReplies;
    }

    /**
     * 新增关键词回复
     *
     * @param botKeyWordReply 关键词回复
     * @return 结果
     */
    @Override
    public int insertBotKeyWordReply(BotKeyWordReply botKeyWordReply)
    {
        botKeyWordReplyMapper.insert(botKeyWordReply);
        return groupCacheRefreshProducer.sendMessage(botKeyWordReply.getChatId());
    }

    /**
     * 修改关键词回复
     *
     * @param botKeyWordReply 关键词回复
     * @return 结果
     */
    @Override
    public int updateBotKeyWordReply(BotKeyWordReply botKeyWordReply)
    {
        LambdaQueryWrapper<BotKeyWordReply> queryWrapper = new LambdaQueryWrapper<>(BotKeyWordReply.class).select(BotKeyWordReply::getKeyWord).eq(BotKeyWordReply::getChatId, botKeyWordReply.getChatId());
        if(botKeyWordReply.getId()!=null){
            //不等于
            queryWrapper.ne(BotKeyWordReply::getId,botKeyWordReply.getId());
        }
        //查询是否已经包含有违禁词
        List<BotKeyWordReply> list = botKeyWordReplyMapper.selectList(queryWrapper);
        List<String> keyList = new ArrayList<>();
        for (BotKeyWordReply keyWordReply : list) {
            keyList.addAll(StrUtil.splitTrim(keyWordReply.getKeyWord(),","));
        }
        //checkKeyWordList去除重复的值
        List<String> checkKeyWordList = StrUtil.splitTrim(botKeyWordReply.getKeyWord(),",").stream().distinct().collect(Collectors.toList());
        
        for (String key : checkKeyWordList) {
            if(keyList.contains(key)){
                throw new ServiceException("操作失败，已存在关键词："+key);
            }
        }
        
        botKeyWordReply.setKeyWord(StrUtil.join(",",checkKeyWordList));
        if(botKeyWordReply.getId()==null){
          return insertBotKeyWordReply(botKeyWordReply);
        }
        botKeyWordReplyMapper.updateById(botKeyWordReply);
        return groupCacheRefreshProducer.sendMessage(botKeyWordReply.getChatId());
    }

    /**
     * 批量删除关键词回复
     *
     * @param ids 需要删除的关键词回复主键
     * @return 结果
     */
    @Override
    public int deleteBotKeyWordReplyByIds(Long[] ids)
    {
        List<Long> idList = Arrays.asList(ids);
        List<BotKeyWordReply> botKeyWordReplies = botKeyWordReplyMapper.selectList(new LambdaQueryWrapper<BotKeyWordReply>().select(BotKeyWordReply::getChatId).in(BotKeyWordReply::getId, idList));
        botKeyWordReplyMapper.deleteByIds(idList);
        List<Long> chatIds = botKeyWordReplies.stream().map(BotKeyWordReply::getChatId).collect(Collectors.toList());
        groupCacheRefreshProducer.sendMessage(chatIds);
        return ids.length;
    }

    /**
     * 删除关键词回复信息
     *
     * @param id 关键词回复主键
     * @return 结果
     */
    @Override
    public int deleteBotKeyWordReplyById(Long id)
    {
        BotKeyWordReply botKeyWordReply = botKeyWordReplyMapper.selectById(id);
        botKeyWordReplyMapper.deleteById(id);
        
        return groupCacheRefreshProducer.sendMessage(botKeyWordReply.getChatId());
    }
    
    /**
     * 检测群组消息是否有自动回复的
     *
     * @param words
     * @param botId
     * @param chatId
     * @param userId
     * @param messageId
     */
    @Override
    public void checkMessageReply(String words, String botId, Long chatId, Long userId, Integer messageId) {
        BotGroup botGroup = getGroupInfo(chatId);
        if(botGroup.getKeyReplyMap()==null){
            return;
        }
        Map<String, String> keyReplyMap = botGroup.getKeyReplyMap();
        //遍历keyReplyMap
        for (String key : keyReplyMap.keySet()) {
            if(words.contains(key)){
                BotKeyboard keyboard = new BotKeyboard(keyReplyMap.get(key));
                send(botId,SendMessage.builder().chatId(chatId).text(keyboard.getContent()).replyToMessageId(messageId).replyMarkup(keyboard.getInlineKeyboardMarkup()).build());
                break;
            }
        }
    }
}
